package client;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @author srh
 * @date 2020/10/18
 **/
public class NIOClient {

    private static final String LOCAL_HOST = "127.0.0.1";
    private static final Integer PORT = 8888;
    private static final Integer BUFFER = 1024;

    private static final String EXIT = "exit";

    public static void main(String[] args) {
        // 创建远程地址
        InetSocketAddress address = new InetSocketAddress(LOCAL_HOST, PORT);
        SocketChannel channel = null;
        // buffer
        ByteBuffer buffer = ByteBuffer.allocate(BUFFER);

        try {
            // 创建连接通道
            channel = SocketChannel.open();
            // 连接远程地址
            channel.connect(address);
            // 输入数据
            System.out.println("please scanner message to send server");
            Scanner scanner = new Scanner(System.in);

            while (true) {
                String line = scanner.nextLine();
                // 停止输入
                if (EXIT.equals(line)) {
                    break;
                }
                // 输入行数据写入到缓存中
                buffer.put(line.getBytes(StandardCharsets.UTF_8));
                // 重置buffer游标
                buffer.flip();
                // 发送数据
                channel.write(buffer);
                buffer.clear();
                System.out.println("client send message = " + line);

                // 读取服务端返回数据
                int readLength = channel.read(buffer);
                if (readLength == -1) {
                    break;
                }
                buffer.flip();
                byte[] bytes = new byte[buffer.remaining()];
                buffer.get(bytes);
                String acceptMessage = new String(bytes, 0, readLength);
                System.out.println("client accept server message = " + acceptMessage);
                buffer.clear();
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

}
